﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Web;
using Shuba.Business;
using Shuba.Model;

namespace Shuba.Web.bulk_upload
{
    public partial class alternate_um_upload : basePage
    {
        private string msg;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("ALTERNATE_UM");

                if (!IsUserAdd(acl))
                {
                    msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }

                LabelTitle.Text = GetPageTitle("ALTERNATE_UM");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                Boolean fileOK = false;
                String path = Server.MapPath("~/uploads/");
                string ErrMessage = "";
                int ErrLine = 0;
                string fName = path + Session["UserID"] + FileUpload1.FileName;
                FileUpload1.PostedFile.SaveAs(fName);

                StreamReader filestream = File.OpenText(fName);
                string contents = filestream.ReadToEnd();
                filestream.Close();

                char rowDelimiter = '\n';
                char fldDelimiter = '\t';

                string[] rows = contents.Split(rowDelimiter);

                //--[+] Validasi untuk format baru file upload (penambahan ACT_TYPE)
                string[] splitHeader = rows[0].Split(fldDelimiter);
                if (splitHeader.Length < 6)
                {
                    msg = GetGlobalResourceObject("Messages", "OldFileAlternateAlert").ToString();
                    lblStatus.Text = msg;
                    status.Visible = true;
                    return;
                }
                //--[-] Penambahan ACT_TYPE format baru file upload


                //for (int a = 1; a < rows.Length; a++)
                //{
                //    string[] fields1 = rows[a].Split(fldDelimiter);

                if (FileUpload1.HasFile)
                {
                    String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedExtensions = {".txt", ".csv"};
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                }

                if (fileOK)
                {
                    status.Visible = true;

                    //string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
                    //FileUpload1.PostedFile.SaveAs(fName);

                    //var filestream = File.OpenText(fName);
                    //string contents = filestream.ReadToEnd();
                    //filestream.Close();

                    var bll = new AlternateUM();
                    AlternateUMInfo Info;

                    var _Branch = new Branch();
                    var _User = new User();
                    string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];
                    string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];

                    //char rowDelimiter = '\n';
                    //char fldDelimiter = '\t';

                    //var rows = contents.Split(rowDelimiter);
                    var AlterNateUMActiveList = new AlternateUMInfo();
                    // Tambahan untuk fix kalau ada error di satu data langsung lanjut ke data lainnya
                    String tempErrMessage = string.Empty;
                    int failed = 0;
                    int success = 0;
                    int stat = 0;
                    int isActive = 0;
                    string fieldActType = "";
                    string tmpbranch = "";
                    string tmpnip = "";
                    string errPosition = string.Empty;
                    try
                    {
                        for (int i = 1; i < rows.Length; i++)
                        {
                            string[] fields = rows[i].Split(fldDelimiter);

                            if (fields.Length > 1)
                            {
                                try
                                {
                                    DateTime dtOut = ProcessingDate().AddDays(-1);
                                    DateTime effDateFrom, effDateTo;

                                    effDateFrom = DateTime.TryParse(fields[3].Trim().Replace(",", ""), out dtOut)
                                        ? Convert.ToDateTime(fields[3].Trim().Replace(",", ""))
                                        : ProcessingDate().AddDays(-1);
                                    effDateTo = DateTime.TryParse(fields[4].Trim().Replace(",", ""), out dtOut)
                                        ? Convert.ToDateTime(fields[4].Trim().Replace(",", ""))
                                        : ProcessingDate().AddDays(-1);

                                    if (_Branch.Get(fields[0].Trim()).BranchName == null){
                                        ErrMessage += "<BR>Invalid Unit, at line :" + i + "";
                                        stat = 1;

                                    }
                                    if (_User.Get(fields[1].Trim(), SPAWEBAppCode).Name == null)
                                    {
                                        if (_User.Get(fields[1].Trim(), SPADAAppCode).Name == null)
                                        {
                                            ErrMessage += "<BR>Invalid NIP, at line :" + i +
                                                          ", Please make sure NIP is correct and already registered in Console Management";
                                            stat = 1;
                                        }
                                    }
                                    AlternateUMInfo AlterNateUMData = bll.GetAlternateUMNotActive(fields[0].Trim(),fields[1].Trim());
                                    AlternateUMInfo AlterNateUMDataTMP = bll.GetTmp(fields[0].Trim(), fields[1].Trim());
                                    List<AlternateUMInfo> AlterNateUMDataList = bll.GetAlternateUMNew(fields[0].Trim(),fields[1].Trim());
                                    
                                    
                                   
                                    if (fields[5].Trim() == "I" || fields[5].Trim() == "")
                                    {
                                        if (AlterNateUMData.NIP != null && AlterNateUMDataTMP.NIP != null && AlterNateUMData.IS_ACTIVE == "1" && AlterNateUMDataTMP.IS_ACTIVE == "1")
                                        {
                                            //if (bll.GetUnionTmp(fields[0].Trim(), fields[1].Trim()).BRANCH_ID !=
                                            //    null)
                                            ErrMessage += "<BR>This NIP is Already Registered, at line :" + i +
                                                          "";
                                            stat = 1;
                                        }
                                        var bi = new AlternateUMInfo();
                                        //if (fields[2].Trim() == "UM")
                                        //{
                                        //    //bi = bll.GetExistingAlternateUM(fields[0].Trim(), fields[1].Trim());

                                        //    //var bil = new List<AlternateUMInfo>();
                                        //    //bil = bll.GetAlternateUM(fields[0].Trim());

                                        //    if (AlterNateUMData.IS_ACTIVE == "1" &&
                                        //        AlterNateUMData.ALTERNATE_FOR == "UM" &&
                                        //        AlterNateUMDataTMP.IS_ACTIVE == "1" &&
                                        //        AlterNateUMDataTMP.ALTERNATE_FOR == "UM")
                                        //    {
                                        //        ////if (bil.Count > 0)
                                        //        //{
                                        //        //    //ErrMessage += "<BR>Alternate UM is already registered in this Unit, at line :" + i + "";


                                        //        //    if (!Validate(bil, effDateFrom, effDateTo))
                                        //        //    {
                                        //        ErrMessage +=
                                        //            "<BR>Alternate UM is already registered in this Unit, at line :" +
                                        //            i + "";
                                        //        //}
                                        //    }
                                        //    stat = 1;
                                        //}
                                    }
                                    if (fields[2].Trim() != "UM" && fields[2].Trim() != "CO" &&
                                        fields[2].Trim() != "LA"){
                                        ErrMessage +=
                                            "<BR>Invalid Alternate, Only UM or CO or LA can be alternate, at line :" +
                                            i + "";
                                            stat = 1;
                                        }

                                    if (fields[5].Trim() != "D")
                                    {
                                        if ((effDateTo.Date < effDateFrom.Date) ||
                                            effDateTo.Date < ProcessingDate().Date ||
                                            effDateFrom.Date < ProcessingDate().Date)
                                        {
                                            ErrMessage += "<BR>Invalid Effective Date, at line :" + i +
                                                          " Please make sure Date is correct, End Date must bigger than Start Date, Minimal date is today";
                                            stat = 1;
                                        }
                                        
                                    }

                                    if (fields[5].Trim() == "D")
                                    {
                                        string errmsgU = "";
                                        foreach (var alternateUmInfo in AlterNateUMDataList)
                                        {
                                            if (alternateUmInfo.IS_ACTIVE == "1")
                                            {
                                                if (tmpbranch == fields[0].Trim() && tmpnip == fields[1].Trim())
                                                {
                                                    errmsgU = "";
                                                }
                                                //if (stat == 0)
                                                //{
                                                //    AlterNateUMActiveList = alternateUmInfo;
                                                //    isActive = 1;
                                                //}
                                                tmpbranch = fields[1].Trim();
                                                tmpnip = fields[2].Trim();

                                            }
                                            else if (alternateUmInfo.IS_ACTIVE == "0")
                                            {
                                                //if (errmsgU !=
                                                //    "<BR>Cannot Update Data, this NIP is InActive, at line :" + i +
                                                //    "")
                                                //{
                                                errmsgU +=
                                                    "<BR>Cannot Delete Data, this NIP is InActive, at line :" +
                                                    i +
                                                    "";
                                                tmpbranch = fields[0].Trim();
                                                tmpnip = fields[1].Trim();

                                                //}
                                            }
                                        }
                                        //if(isActive == 0){
                                        ErrMessage += errmsgU;
                                    }
                                    if (fields[5].Trim() == "U")
                                    {
                                        
                                        string errmsgU = "";
                                        foreach (var alternateUmInfo in AlterNateUMDataList)
                                        {
                                           if (alternateUmInfo.IS_ACTIVE == "1")
                                           {
                                               if (tmpbranch == fields[0].Trim() && tmpnip == fields[1].Trim())
                                               {
                                                   errmsgU = "";
                                               }
                                               //if (stat == 0)
                                               //{
                                               //    AlterNateUMActiveList = alternateUmInfo;
                                               //    isActive = 1;
                                               //}
                                               tmpbranch = fields[1].Trim();
                                               tmpnip = fields[2].Trim();
                                                    
                                            }
                                            else if (alternateUmInfo.IS_ACTIVE == "0")
                                            {
                                                //if (errmsgU !=
                                                //    "<BR>Cannot Update Data, this NIP is InActive, at line :" + i +
                                                //    "")
                                                //{
                                                    errmsgU +=
                                                        "<BR>Cannot Update Data, this NIP is InActive, at line :" +
                                                        i +
                                                        "";
                                                    tmpbranch = fields[0].Trim();
                                                    tmpnip = fields[1].Trim();

                                                //}
                                            }
                                        }
                                        //if(isActive == 0){
                                        ErrMessage += errmsgU;
                                        //}
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ErrMessage = ex.Message;
                                    lblStatus.Text = "<BR>Invalid Data Format, at line :" + i + "<br>" +
                                                     ErrMessage;
                                }


                                if (ErrMessage == "")
                                {
                                    Info = new AlternateUMInfo();
                                    if (fields[5].Trim() == "I")
                                    {
                                        fieldActType = "INSERT";
                                    }
                                    else if (fields[5].Trim() == "U")
                                    {
                                        fieldActType = "UPDATE";
                                    }
                                    else if (fields[5].Trim() == "D")
                                    {
                                        fieldActType = "DELETE";
                                    }
                                    try
                                    {
                                        DateTime cad = ProcessingDate();
                                        Info.BRANCH_ID = fields[0].Trim();
                                        Info.NIP = fields[1].Trim();
                                        Info.ALTERNATE_FOR = fields[2].Trim();
                                        Info.EFF_DATE_FROM = DateTime.TryParse(fields[3].Trim(), out cad)
                                            ? Convert.ToDateTime(fields[3].Trim())
                                            : ProcessingDate();
                                        Info.EFF_DATE_TO = DateTime.TryParse(fields[4].Trim(), out cad)
                                            ? Convert.ToDateTime(fields[4].Trim())
                                            : ProcessingDate();
                                        Info.ACT_TYPE = fields[5].Trim() == null ? "INSERT" : fieldActType;
                                        Info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                                        Info.ENTRY_DATE = ProcessingDate();
                                        Info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                                        Info.UPDATE_DATE = ProcessingDate();
                                        Info.IS_ACTIVE = "1";
                                        Info.BRANCH_ID_ORIG = fields[0].Trim();
                                        Info.NIP_ORIG = fields[1].Trim();
                                        Info.ALTERNATE_FOR_ORIG = fields[2].Trim();
                                        Info.EFF_DATE_FROM_ORIG = DateTime.TryParse(fields[3].Trim(), out cad)
                                            ? Convert.ToDateTime(fields[3].Trim())
                                            : ProcessingDate();
                                        Info.EFF_DATE_TO_ORIG = DateTime.TryParse(fields[4].Trim(), out cad)
                                            ? Convert.ToDateTime(fields[4].Trim())
                                            : ProcessingDate();

                                        bll.Save(Info);

                                        success++;
                                    }
                                    catch (Exception ex)
                                    {
                                        ErrMessage += ex.Message;
                                    }
                                }
                                
                                //else if (AlterNateUMActiveList != null && stat == 0 && isActive == 1)
                                //{
                                //    Info = new AlternateUMInfo();
                                //    if (fields[5].Trim() == "I")
                                //    {
                                //        fieldActType = "INSERT";
                                //    }
                                //    else if (fields[5].Trim() == "U")
                                //    {
                                //        fieldActType = "UPDATE";
                                //    }
                                //    else if (fields[5].Trim() == "D")
                                //    {
                                //        fieldActType = "DELETE";
                                //    }
                                //    try
                                //    {
                                //        DateTime cad = ProcessingDate();
                                //        Info.BRANCH_ID = fields[0].Trim();
                                //        Info.NIP = fields[1].Trim();
                                //        Info.ALTERNATE_FOR = fields[2].Trim();
                                //        Info.EFF_DATE_FROM = DateTime.TryParse(fields[3].Trim(), out cad)
                                //            ? Convert.ToDateTime(fields[3].Trim())
                                //            : ProcessingDate();
                                //        Info.EFF_DATE_TO = DateTime.TryParse(fields[4].Trim(), out cad)
                                //            ? Convert.ToDateTime(fields[4].Trim())
                                //            : ProcessingDate();
                                //        Info.ACT_TYPE = fields[5].Trim() == null ? "INSERT" : fieldActType;
                                //        Info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                                //        Info.ENTRY_DATE = ProcessingDate();
                                //        Info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                                //        Info.UPDATE_DATE = ProcessingDate();
                                //        Info.IS_ACTIVE = "1";
                                //        Info.BRANCH_ID_ORIG = fields[0].Trim();
                                //        Info.NIP_ORIG = fields[1].Trim();
                                //        Info.ALTERNATE_FOR_ORIG = fields[2].Trim();
                                //        Info.EFF_DATE_FROM_ORIG = DateTime.TryParse(fields[3].Trim(), out cad)
                                //            ? Convert.ToDateTime(fields[3].Trim())
                                //            : ProcessingDate();
                                //        Info.EFF_DATE_TO_ORIG = DateTime.TryParse(fields[4].Trim(), out cad)
                                //            ? Convert.ToDateTime(fields[4].Trim())
                                //            : ProcessingDate();

                                //        bll.Save(Info);

                                //        success++;
                                        
                                //    }
                                //    catch (Exception ex)
                                //    {
                                //        ErrMessage += ex.Message;
                                //    }
                                //}
                                else
                                {
                                    ErrLine = i;
                                    //i = rows.Length;
                                    failed++;

                                    errPosition += (failed == 1) ? i.ToString() : ", " + i;
                                }
                                tempErrMessage += ErrMessage;
                                ErrMessage = string.Empty;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrMessage += "<br>" + GetGlobalResourceObject("Messages", "UploadFailAlert");
                        ErrMessage += "<br>" + ex.Message +
                                      "<br>Please check your data, and put \"space\" in HP column at Row 1";
                    }

                    File.Delete(fName);
                    AddLog("UPLOAD", "UPLOAD ALTERNATE UM");

                    ErrMessage += tempErrMessage;
                    if (ErrMessage == "")
                    {
                        msg = GetGlobalResourceObject("Messages", "UploadSuccessAlert").ToString();
                        lblStatus.Text = msg;
                        FileUpLoadValidator.Visible = false;
                        AlertAndRedirect(msg, "alternate_um_list.aspx");
                    }
                    else
                    {
                        ErrMessage += "<br>" + GetGlobalResourceObject("Messages", "UploadFailAlert");
                        //lblStatus.Text = "<b>Error Found:</b><br>" + ErrMessage + "<br><br><b>Upload Process Stoped at Line: " + ErrLine + "</b>";
                        lblStatus.Text = ErrMessage + "<br>" +
                                         string.Format(
                                             "<b>Success: {0}</b><br><b>Failed: {1}</b><br><b>Error found: Line {2}</b>",
                                             success, failed, errPosition);
                        FileUpLoadValidator.Visible = false;
                    }
                }
                else
                {
                    msg = GetGlobalResourceObject("Messages", "UploadInvalidFileAlert").ToString();
                    lblStatus.Text = msg;
                }
                //}
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("alternate_um_list.aspx");
        }

        private bool Validate(List<AlternateUMInfo> list, DateTime StartFromEntry, DateTime StartToEntry)
        {
            var Entry = new List<DateTime>();
            for (DateTime i = StartFromEntry.Date; i <= StartToEntry.Date; i = i.AddDays(1))
            {
                Entry.Add(i);
            }

            foreach (AlternateUMInfo bi in list)
            {
                var Existing = new List<DateTime>();
                for (DateTime i = bi.EFF_DATE_FROM.Date; i <= bi.EFF_DATE_TO.Date; i = i.AddDays(1))
                {
                    Existing.Add(i);
                }

                foreach (DateTime item in Entry)
                {
                    if (Existing.Contains(item))
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}